package com.jgc.blockingqueue;

import java.util.concurrent.PriorityBlockingQueue;

/**
 *
 PriorityBlockingQueue 是 Java 中的一个线程安全的优先级队列实现，它是基于优先级堆的数据结构实现的。
 与普通的队列不同，优先级队列中的元素是按照它们的优先级顺序排列的，而不是按照它们被插入到队列中的顺序排列的
 */
public class PriorityBlockingQueueTest {

    // 自定义任务类，实现 Comparable 接口
    static class Task implements Comparable<Task> {
        private String name;
        private int priority;

        public Task(String name, int priority) {
            this.name = name;
            this.priority = priority;
        }

        public String getName() {
            return name;
        }

        public int getPriority() {
            return priority;
        }

        // 实现 compareTo 方法，定义任务之间的比较规则
        @Override
        public int compareTo(Task other) {
            return Integer.compare(other.priority, this.priority); // 按照优先级从高到低排序
        }

    }

    public static void main(String[] args) throws InterruptedException {
        PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>(20);
        // 向队列中添加任务
//        queue.add(new Task("Task 1", 5));
//        queue.add(new Task("Task 2", 3));
//        queue.add(new Task("Task 3", 8));
//        queue.add(new Task("Task 4", 1));
        Thread addBatchTaskThread = new Thread(()->{
            for (int i = 0; i < 100; i++) {
                queue.add(new Task("批量任务",1));
                /*try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }*/
            }
        });

        Thread addLiveTaskThread = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                queue.add(new Task("实时请求1",99));
            }
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                queue.add(new Task("实时请求2",99));
            }
        });
        addBatchTaskThread.start();
        addLiveTaskThread.start();
        while (true){
            Thread.sleep(10);
            Task task = queue.poll();
            if(task!=null){
                System.out.println("Task Name: " + task.getName() + ", Priority: " + task.getPriority());
            } else {
                System.out.println("queue is Empty");
            }
            Thread.sleep(1000);
        }
    }

}

